<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>商品分类</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片区域 -->
        <el-card>
            <!-- 添加角色按钮区域 -->
            <el-row>
                <el-button type="primary" @click='addList'>添加分类</el-button>
            </el-row>
            <!-- 表格区域 -->
            <tree-table :data='cateList' :columns="columns" show-index index-text='' :expand-type='false'
                :selection-type='false' border>
                <!-- 是否有效 -->
                <template slot="isok" slot-scope="scope">
                    <i class="el-icon-success" v-if='scope.row.cat_deleted === false' style="color: lightgreen;"></i>
                    <i class="el-icon-error" v-else style="color: red;"></i>
                </template>
                <!-- 排序 -->
                <template slot="order" slot-scope='scope'>
                    <el-tag size='mini' v-if='scope.row.cat_level===0'>一级</el-tag>
                    <el-tag type="success" size='mini' v-else-if='scope.row.cat_level===1'>二级</el-tag>
                    <el-tag type="warning" size='mini' v-else>三级</el-tag>
                </template>
                <!-- 操作 -->
                <template slot="operation" slot-scope='scope'>
                    <el-button type="primary" icon="el-icon-edit" size='mini' @click=editList(scope.row.cat_id)>编辑
                    </el-button>
                    <el-button type="danger" icon="el-icon-delete" size='mini' @click=removeList(scope.row.cat_id)>删除
                    </el-button>
                </template>
            </tree-table>
            <!-- 分页区域 -->
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="queryInfo.pagenum" :page-sizes="[3, 5, 10, 15]" :page-size="queryInfo.pagesize"
                layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </el-card>
        <!-- 添加分类弹框 -->
        <el-dialog title="添加分类" :visible.sync="addDialogVisible" width="40%" @close='addDialogVisibleClose'>
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="80px">
                <el-form-item label="分类名称" prop="cat_name">
                    <el-input v-model="addForm.cat_name"></el-input>
                </el-form-item>
                <el-form-item label="父级分类" prop='cat_pid'>
                    <el-cascader v-model="selectKeys" :options="parentCateList" :props="cascaderProps"
                        @change="cascaderChange" clearable>
                    </el-cascader>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addCascader">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 编辑分类弹框 -->
        <el-dialog title="修改分类" :visible.sync="editDialogVisible" width="40%" @close='editDialogVisibleClose'>
            <el-form :model="EditForm" :rules="EditFormRules" ref="editFormRef" label-width="80px">
                <el-form-item label="分类名称" prop="cat_name">
                    <el-input v-model="EditForm.cat_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editCascader">确 定</el-button>
            </span>
        </el-dialog>

    </div>
</template>

<script>
    export default {
        data() {
            return {
                // 要传递的参数
                queryInfo: {
                    type: 3,
                    pagenum: 1,
                    pagesize: 5
                },
                // 商品数据列表
                cateList: [],
                // 总数据条数
                total: 0,
                columns: [{
                    label: '分类名称',
                    prop: 'cat_name'
                }, {
                    label: '是否有效',
                    // 决定当前列为模板列
                    type: 'template',
                    // 表示当前列的使用名称
                    template: 'isok',
                }, {
                    label: '排序',
                    // 决定当前列为模板列
                    type: 'template',
                    // 表示当前列的使用名称
                    template: 'order',
                }, {
                    label: '操作',
                    // 决定当前列为模板列
                    type: 'template',
                    // 表示当前列的使用名称
                    template: 'operation',
                }],
                // 控制添加分类弹框是否显示
                addDialogVisible: false,
                // 添加分类的表单数据对象
                addForm: {
                    cat_name: '',
                    cat_pid: 0,
                    cat_level: 0
                },
                addFormRules: {
                    cat_name: [
                        { required: true, message: '请输入分类名称', trigger: 'blur' },
                    ]
                },
                // 父级分类的数据列表
                parentCateList: [],
                // 指定级联选择器的配置对象
                cascaderProps: {
                    expandTrigger: 'hover',
                    checkStrictly: true,
                    value: 'cat_id',
                    label: 'cat_name',
                    children: 'children'
                },
                // 选中的父级分类的id 数组
                selectKeys: [],
                // 控制编辑分类弹框是否显示
                editDialogVisible: false,
                EditForm: {
                    cat_name: '',
                    cat_id: 0
                },
                EditFormRules: {
                    cat_name: [
                        { required: true, message: '请输入分类名称', trigger: 'blur' },
                    ]
                }

            }
        },
        created() {
            this.getCateList();
        },
        methods: {
            // 获取商品分类列表
            async getCateList() {
                const { data: res } = await this.$axios.get('categories', { params: this.queryInfo });
                if (res.meta.status !== 200) return this.$message.error('获取商品列表失败');
                // console.log(res.data);
                this.cateList = res.data.result;
                this.total = res.data.total;
            },
            handleSizeChange(newSize) {
                this.queryInfo.pagesize = newSize;
                this.getCateList();
            },
            handleCurrentChange(newPage) {
                this.queryInfo.pagenum = newPage;
                this.getCateList();
            },
            // 关闭添加分类弹框 重置表单
            addDialogVisibleClose() {
                this.$refs.addFormRef.resetFields();
                this.selectKeys = [];
                this.addForm.cat_pid = 0;
                this.addForm.cat_level = 0;
            },
            // 添加分类
            addList() {
                // 先获取父级分类数据
                this.getParentCateList();
                // 再显示弹框
                this.addDialogVisible = true;
            },
            // 获取父级分类数据
            async getParentCateList() {
                const { data: res } = await this.$axios.get('categories', { params: { type: 2 } });
                if (res.meta.status !== 200) return this.$message.error('获取父级分类失败');
                this.parentCateList = res.data;
                // console.log(res.data);
            },
            // 选择项发生变化触发这个函数
            cascaderChange() {
                console.log(this.selectKeys)
                if (this.selectKeys.length !== 0) {
                    this.addForm.cat_pid = this.selectKeys[this.selectKeys.length - 1];
                    this.addForm.cat_level = this.selectKeys.length;
                } else {
                    this.addForm.cat_pid = 0;
                    this.addForm.cat_level = 0;
                }
                return
            },
            // 点击确定发送添加分类请求
            addCascader() {
                // 预验证
                this.$refs.addFormRef.validate(async valid => {
                    if (!valid) return
                    const { data: res } = await this.$axios.post('categories', this.addForm);
                    if (res.meta.status !== 201) return this.$message.error('添加失败');
                    this.$message.success('添加成功');
                    this.getCateList();
                    this.addDialogVisible = false;
                })
            },
            // 关闭编辑分类弹框 重置表单
            editDialogVisibleClose() {
                this.$refs.editFormRef.resetFields();
            },
            // 根据id 查询分类信息
            async editList(id) {
                this.EditForm.cat_id = id;
                const { data: res } = await this.$axios.get(`categories/${ id }`);
                if (res.meta.status !== 200) return this.$message.error('获取父级分类失败');
                this.EditForm = res.data;
                // console.log(res.data);
                this.editDialogVisible = true;
            },
            // 点击确定发送编辑分类请求
            editCascader() {
                // 预验证
                this.$refs.editFormRef.validate(async valid => {
                    if (!valid) return
                    const { data: res } = await this.$axios.put(`categories/${ this.EditForm.cat_id }`, {
                        cat_name: this.EditForm.cat_name
                    });
                    if (res.meta.status !== 200) return this.$message.error('修改失败');
                    this.$message.success('修改成功');
                    this.getCateList();
                    this.editDialogVisible = false;
                });
            },
            // 删除分类
            async removeList(id) {
                const confirmRefult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(err => err);
                if (confirmRefult !== 'confirm') return this.$message.info('已取消删除');
                const { data: res } = await this.$axios.delete(`categories/${ id }`)
                if (res.meta.status !== 200) return this.$message.error('删除失败');
                this.$message.success('删除成功');
                this.getCateList();
            }
        }
    }
</script>

<style scoped>
    .el-row {
        margin-bottom: 15px;
    }

    .el-pagination {
        margin-top: 15px;
    }

    .el-cascader {
        width: 100%;
    }
</style>